<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="csrf-token" content="{{ csrf_token() }}">

		
		<!-- <link rel="stylesheet" href="{{ asset("/custom-templates/plugins/bootstrap/bootstrap.min.css") }}"> -->
		<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
		<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
		<!-- select2 -->
		<link rel="stylesheet" href="{{ asset("/custom-templates/plugins/select2/css/select2.min.css") }}">
		<link rel="stylesheet" href="{{ asset("/custom-templates/plugins/select2/css/s2-docs.css") }}">
		<!-- bootstrap-datetimepicker -->
		<link rel="stylesheet" href="{{ asset("/custom-templates/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css") }}">

		<!-- datatables -->
		<!-- <link href="../css/admin/bootstrap.min.css" rel="stylesheet" type="text/css"/> -->
		<link href="{{ asset("/custom-templates/datatables/css/css3/animate.css") }}" rel="stylesheet" type="text/css"/>
		<link href="{{ asset("/custom-templates/datatables/css/fonts.css") }}" rel="stylesheet" type="text/css"/>
		<link href="{{ asset("/custom-templates/datatables/css/icons.css") }}" rel="stylesheet" type="text/css"/>
		<link href="{{ asset("/custom-templates/datatables/css/admin/style.css") }}" rel="stylesheet" type="text/css"/>
		<link href="{{ asset("/custom-templates/datatables/css/admin/jquery.dataTables.css") }}" rel="stylesheet" type="text/css"/>
		<link rel="stylesheet" href="{{ asset("/custom-templates/css/reset.css") }}">
		<link rel="stylesheet" href="{{ asset("/custom-templates/css/area.css") }}">
		<link rel="stylesheet" href="{{ asset("/custom-templates/css/biz/p3.css") }}">
    </head>
    <body>
    	<!-- 模板容器 -->
		<div id="custom-template-wrap">
		</div>

		<div class="container">
			<form>
				<!-- 开始时间 -->
				<div class="form-group">
					<label for="start_time">开始时间</label>
					<input type="text" class="form-control" id="start_time" placeholder="请选择时间">
				</div>
				<!-- 结束时间 -->
				<div class="form-group">
					<label for="end_time">结束时间</label>
					<input type="text" class="form-control" id="end_time" placeholder="请选择时间">
				</div>
				<!-- 保存按钮 -->
				<a href="javascript:void(0);" class="btn btn-default" id="submit">Submit</a>
			</form>
		</div>



		<!-- Modal -->
		<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
		  <div class="modal-dialog modal-lg" role="document">
		    <div class="modal-content">
		      <div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		        <h4 class="modal-title">该区域需要选择<span id="video_count"></span>个视频</h4>
		      </div>
		      <div class="modal-body">
				<form>
					<!-- 视频 -->
					<div class="form-group">
						<label for="videos">视频列表</label>
						<select class="form-control" id="videos" style="width: 100%;">
				  			<!-- <option value="3620194" selected="selected">select2/select2</option> -->
						</select>
					</div>
				</form>
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
		        <button type="button" class="btn btn-primary" id="save">保存</button>
		      </div>
		    </div><!-- /.modal-content -->
		  </div><!-- /.modal-dialog -->
		</div><!-- /.modal -->

		<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
        <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
        <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <!-- <script type="text/javascript" src="{{ asset("/custom-templates/js/ui_json.js") }}"></script> -->
        <!-- select2 -->
        <script type="text/javascript" src="{{ asset("/custom-templates/plugins/select2/js/select2.min.js") }}"></script>
        <!-- bootstrap-datetimepicker -->
        <script type="text/javascript" src="{{ asset("/custom-templates/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js") }}"></script>
        <!-- store.js -->
        <script type="text/javascript" src="https://cdn.bootcss.com/store.js/1.3.20/store.min.js"></script>
    
        

        <!-- datatables -->
        <!-- <script src="{{ asset("/custom-templates/datatables/js/jquery.min.js") }}" type="text/javascript"></script> -->
        <!-- <script src="{{ asset("/custom-templates/datatables/js/admin/bootstrap.min.js") }}" type="text/javascript"></script> -->
        <script src="{{ asset("/custom-templates/datatables/js/admin/jquery.dataTables.js") }}" type="text/javascript"></script>
        <script src="{{ asset("/custom-templates/datatables/js/admin/dataTables.bootstrap.js") }}" type="text/javascript"></script>
        <script src="{{ asset("/custom-templates/datatables/js/admin/colResizable-1.5.min.js") }}" type="text/javascript"></script>

        <script type="text/javascript" src="{{ asset("/custom-templates/js/api/api.js") }}"></script>
        <script type="text/javascript" src="{{ asset("/custom-templates/js/api/config.js") }}"></script>
        <script type="text/javascript" src="{{ asset("/custom-templates/js/biz/subject001.js") }}"></script>
        <script type="text/javascript" src="{{ asset("/custom-templates/js/comm_interaction.js") }}"></script>
		<script type="text/javascript">
			$(function() {
				// 渲染模板
				// $("#custom-template-wrap").html("<div id='AREA002' style='width:1280px;height:488px;margin:auto;background:'>"+getAreaHtml(areaJson,"AREA002")+"</div>");
				initSubject001();
				// 有几块区域需要编辑
				var divs = ["subjectList","subjectCont"];
				window.OPTIONS = {
					"subjectList": {
						"options_url": "/videos",// 数据来源
						"count": 4,// 资源个数
						"area": "subjectList",
						"mapping": {// 数据映射

						}
					},
					"subjectCont": {
						"options_url": "/videos",// 数据来源
						"count": 1,// 资源个数
						"area": "subjectCont",
						"mapping": {// 数据映射

						}
					}
				};

				// 解决selec2无法在输入框搜索的问题
				$.fn.modal.Constructor.prototype.enforceFocus = function () { };

				// 时间控件渲染
				var newDate = new Date();
    			var t       = newDate.toJSON();
				$('#start_time').datetimepicker({
					format: 'yyyy-mm-dd HH:ii:ss',
					language:  'fr',
					weekStart: 1,
					todayBtn:  1,
					autoclose: 1,
					todayHighlight: 1,
					startView: 2,
					minView: 2,
					forceParse: 0,
					weekStart: 1,
					showMeridian: 1,
					minuteStep : 1,
					startDate:new Date(t),
				});
				$('#end_time').datetimepicker({
					format: 'yyyy-mm-dd HH:ii:ss',
					language:  'fr',
					weekStart: 1,
					todayBtn:  1,
					autoclose: 1,
					todayHighlight: 1,
					startView: 2,
					minView: 2,
					forceParse: 0,
					weekStart: 1,
					showMeridian: 1,
					minuteStep : 1,
					startDate:new Date(t),
				});

				// 给需要编辑的区域绑定点击事件
				$.each(divs, function(index, item) {
					console.log(item);
					$("#" + item).on("click", function(e) {
						console.log(window.OPTIONS);
						var option = window.OPTIONS[item];
						// 要选几个视频
						$("#video_count").text(option.count);
						// 记录下现在是编写那块区域的数据
						store.set('current_area', item);
						console.log(store.get('current_area'));
						console.log(option);
						console.log(item);
						console.log(e);
						$('#videos').val("");
						// 拉取视频数据
						$("#videos").select2({
							// 多语言
							allowClear: true,
							language: "zh-CN",
						    placeholder          : "请输入",
							multiple             : true,
						    minimumInputLength   : 1,
						    separator            : ",",// 分隔符
						    maximumSelectionSize : option.count, // 限制数量
							ajax: {
								url: option.options_url,//"/videos",
								dataType: 'json',
								delay: 250,
								data: function (params) {
									return {
										q: params.term, // search term
										page: params.page
									};
								},
								processResults: function (data, params) {
									// parse the results into the format expected by Select2
									// since we are using custom formatting functions we do not need to
									// alter the remote JSON data, except to indicate that infinite
									// scrolling can be used
									params.page = params.page || 1;

									return {
										results: data.results,
										pagination: {
											more: (params.page * 30) < data.total_count
										}
									};
								},
								cache: true
							},
							escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
							minimumInputLength: 1,
							templateResult: formatRepo, // omitted for brevity, see the source of this page
							templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
						});

						// $('#userSelect').select2({
						//     placeholder          : "请输入",
						//     minimumInputLength   : 1,
						//     multiple             : true,
						//     separator            : "^",                             // 分隔符
						//     maximumSelectionSize : 5,                               // 限制数量
						//     initSelection        : function (element, callback) {   // 初始化时设置默认值
						//         var data = [];
						//         $(element.val().split("^")).each(function () {
						//             data.push({id: this, text: this});
						//         });
						//         callback(data);
						//     },
						//     createSearchChoice   : function(term, data) {           // 创建搜索结果（使用户可以输入匹配值以外的其它值）
						//         return { id: term, text: term };
						//     },
						//     formatSelection : function (item) { return item.id; },  // 选择结果中的显示
						//     formatResult    : function (item) { return item.id; },  // 搜索列表中的显示
						//     ajax : {
						//         url      : "test-api",              // 异步请求地址
						//         dataType : "json",                  // 数据类型
						//         data     : function (term, page) {  // 请求参数（GET）
						//             return { q: term };
						//         },
						//         results      : function (data, page) { return data; },  // 构造返回结果
						//         escapeMarkup : function (m) { return m; }               // 字符转义处理
						//     }
						// });
						
						// 打开模态框
						$('#myModal').modal('show');

					});
					console.log(index);
					console.log(item);
				});
	
				// 格式化
			    function formatRepo (repo) {
			      if (repo.loading) return repo.text;

			      var markup = "<div class='select2-result-repository clearfix'>" +
			        "<div class='select2-result-repository__avatar'><img src='" + repo.imgurl + "' /></div>" +
			        "<div class='select2-result-repository__meta'>" +
			          "<div class='select2-result-repository__title'>" + repo.title + "</div>";

			      if (repo.description) {
			        markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
			      }

			      // markup += "<div class='select2-result-repository__statistics'>" +
			      //   "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
			      //   "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
			      //   "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
			      // "</div>" +
			      // "</div></div>";

			      return markup;
			    }

				function formatRepoSelection (repo) {
					return repo.title || repo.subtitle;
				}

				// 保存每块区域的数据
				$('#save').on('click', function () {
					var current_area = store.get('current_area');
					if (!current_area) {
						alert("没有选中要编写数据的区域!");
						return false;
					}
					var option = window.OPTIONS[current_area];
					// 判断下选中的视频数和需要的视频数是否相等
					if ($('#videos').select2('data').length != option.count) {
						alert("所选的视频数量和该区域需要的视频数量不一致, 该区域需要" + option.count + "个视频!");
						return false;
					}
					// var str2value= $("#select2").select2("val");
					console.log($('#videos').select2('data'));

					// Demo: Circular reference
					var o = {};
					// Note: cache should not be re-used by repeated calls to JSON.stringify.
					var cache = [];
					var data = JSON.stringify($('#videos').select2('data'), function(key, value) {
					    if (typeof value === 'object' && value !== null) {
					        if (cache.indexOf(value) !== -1) {
					            // Circular reference found, discard key
					            return;
					        }
					        // Store value in our collection
					        cache.push(value);
					    }
					    return value;
					});
					cache = null; // Enable garbage collection
					console.log(data);
					// 将每块区域的数据保存到localstorage
					store.set(option.area, data);
					// 关闭模态框
					$('#myModal').modal('hide');
					//将选择后的数据填充对应区域
					fillArea(option.area, data);

				});

				// 防止csrf
				$.ajaxSetup({
				    headers: {
				        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
				    }
				});

				// 提交
				$('#submit').on('click', function() {
					var content = {};
					var start_time;
					var end_time;
					var flag = false;
					// 判断每块区域的视频数是否满足要求了
					$.each(divs, function(index, item) {
						var option = window.OPTIONS[item];
						var data = JSON.parse(store.get(option.area));
						console.log(data);
						if (data.length != option.count) {
							alert("区域:" + item + ",所选的视频数量和需要的视频数量不一致, 该区域需要" + option.count + "个视频!");
							flag = true;
							return false;
						}
						content[option.area] = data;
						
					});

					if (flag) {
						return true;
					}

					start_time = $("#start_time").val();
					if (!start_time) {
						alert("请选择开始时间!");
						return false;
					}
					end_time = $("#end_time").val();
					if (!end_time) {
						alert("请选择结束时间!");
						return false;
					}
					console.log(content);
					console.log(start_time);
					console.log(end_time);

					// 保存数据
					$.ajax({
						type: "POST",
						url: "/save",
						data: {
							template_type: "AREA",
							template_no: "001",
							content: content,
							start_time: start_time,
							end_time: end_time
						},
						dataType: "json",
						success: function(data) {
							console.log(data);
							if (data.status == "success") {
								// store.remove('key');
								// Clear all keys
								// store.clearAll();
								$('#start_time').empty();
								$('#end_time').empty();
								window.history.back(-1);
								// window.location.href;
							} else {
								alert(data.content);
							}
						}
					});
				});


			    function formatRepo1 (repo) {
			      if (repo.loading) return repo.text;

			      var markup = "<div class='select2-result-repository clearfix'>" +
			        "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
			        "<div class='select2-result-repository__meta'>" +
			          "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

			      if (repo.description) {
			        markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
			      }

			      markup += "<div class='select2-result-repository__statistics'>" +
			        "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
			        "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
			        "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
			      "</div>" +
			      "</div></div>";

			      return markup;
			    }

				function formatRepoSelection1 (repo) {
					return repo.full_name || repo.text;
				}
			});
		</script>
    </body>
</html>
